<template>
  <div class="wrapper">
    <!-- <Anchor class="mainAnchor" :labelList="labels" activeId="row-01" labelWidth="80">
    <div class="line" id="row-01" style="min-height:780px">-->
    <BreakSpace :label="labels[0].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoBase
      ref="infoBase"
      :formType="value.type"
      :formOptions="value"
      v-model="formData"
      @formchange="infoBaseChange"
    />
    <!-- </div>
    <div class="line" id="row-02">-->
    <BreakSpace :label="labels[1].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoProduct
      ref="infoProduct"
      :formType="value.type"
      :formOptions="value"
      v-model="formData"
      @formchange="infoProductChange"
    />
    <!-- </div>
    <div class="line" id="row-03" style="min-height:780px">-->
    <BreakSpace :label="labels[2].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoPower
      ref="infoPower"
      :formType="value.type"
      :formOptions="value"
      v-model="formData"
      @formchange="infoPowerChange"
    />
    <!-- </div>
    <div class="line" id="row-04">-->
    <BreakSpace :label="labels[3].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoCompany
      ref="infoCompany"
      :formType="value.type"
      :formOptions="value"
      v-model="formData"
      @formchange="infoCompanyChange"
    />
    <!-- </div>
    <div class="line" id="row-05">-->
    <BreakSpace :label="labels[4].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoStock
      ref="infoStock"
      :formType="value.type"
      :formOptions="value"
      v-model="formData"
      @formchange="infoStockChange"
    />
    <!-- </div>
    <div class="line" id="row-06">-->
    <BreakSpace :label="labels[5].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoFinance
      ref="infoFinance"
      :formType="value.type"
      :formOptions="value"
      v-model="formData"
      @formchange="infoFinanceChange"
    />
    <!-- </div> -->
    <!-- <div class="line" id="row-07">
				<infoOpinion ref="infoOpinion" :formType="value.type" v-model="formData" @formchange="infoOpinionChange"/>
    </div>-->
    <!-- </Anchor> -->
    <div class="dialogBottmView">
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button @click="saveDialog()" v-if="value.type!=='show'" type="primary">保 存</el-button>
      <!-- <el-button @click="determineDialog()" v-if="value.type!=='show'" :disabled="this.formData.status === this.types.DEALER_INFO_STATUS_ENABLE" type="primary">确 定</el-button> -->
      <el-button @click="determineDialog()" v-if="value.type!=='show'" type="primary">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { authority } from '@/utils/authMixin';
import { dictionary } from '@/utils/dictMixin';
import autoLoding from '@/utils/loding'; //等待框
import infoBase from '../dealerFormView/infoBase'; //基本信息
import infoProduct from '../dealerFormView/infoProduct'; //产品授权
import infoPower from '../dealerFormView/infoPower'; //授权信息
import infoCompany from '../dealerFormView/infoCompany'; //公司信息
import infoStock from '../dealerFormView/infoStock'; //股东信息
import infoFinance from '../dealerFormView/infoFinance'; //财务信息
// import infoOpinion from '../dealerFormView/infoOpinion'; //审核信息

import { getDetails } from '@/api/cms-api/origin/originInfo';
import { addAllData, editAllData, addDetermine, editDetermine } from '@/api/cms-api/origin/originInfo/OEM';
import * as types from '@/api/cms-api/origin/originInfo/types';
import { dealerCommon } from '@/api/cms-api/origin/commonDealerType'; //经销商类型工具类
import { isArray } from 'util';

export default {
  mixins: [authority, dictionary, autoLoding, dealerCommon],
  components: {
    infoBase,
    infoProduct,
    infoPower,
    infoCompany,
    infoStock,
    infoFinance
  },
  props: {
    value: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      formData: {},
      labels: [
        { title: '基本信息', id: 'row-01' },
        { title: '产品授权', id: 'row-02' },
        { title: '授权信息', id: 'row-03' },
        { title: '公司信息', id: 'row-04' },
        { title: '股东信息', id: 'row-05' },
        { title: '财务信息', id: 'row-06' }
      ],
      // loadingVm:null,
      types: types
    };
  },
  mounted() {
    //this.loadingVm = this.openLoding('.cover-container');
    if (this.value.type != 'add') {
      //按ID获取数据
      this.init();
    } else {
      //this.closeLoding(this.loadingVm);
    }
  },
  methods: {
    async init() {
      let res = await getDetails(this.value.id, {});
      if (res.resultCode === 200) {
        //转换附件为list<Sting>
        this.formData = this.transformAllEnclosureString(res.data);
        this.formData.inputNumber = '';
        this.formData.inputChar = '';
        this.$nextTick(() => {
          this.$refs.infoBase.init();
          this.$refs.infoProduct.init();
          this.$refs.infoPower.init();
          this.$refs.infoCompany.init();
          this.$refs.infoStock.init();
          this.$refs.infoFinance.init();
          this.closeLoding(this.loadingVm);
        });
      }
    },
    // //打开等待遮罩
    // openLoding(options){
    // 	let defOptions = {	// 声明一个loading对象
    // 		lock: true, // 是否锁屏
    // 		fullscreen: false,
    // 		body: false,
    // 		target: '.mainAnchor', // 需要遮罩的区域
    // 	};
    // 	defOptions = Object.assign(defOptions,options);
    // 	// this.loadingVm = this.$loading(defOptions);
    // 	return this.$loading(defOptions);
    // },
    // //关闭等待遮罩
    // closeLoding(loading){
    // 	loading.close();
    // },
    //确定（验证并提交）
    determineDialog() {
      this.$refs.infoBase.saveDialog();
    },
    //保存（不验证）
    saveDialog() {
      this.loadingVm = this.openLoding('.cover-container');
      //取数据
      let allData = { ...this.formData };

      //@1
      this.$refs.infoBase.$refs.FormPanel.excuteFormData(this.$refs.infoBase.$refs.FormPanel.form);
      allData = Object.assign(allData, this.$refs.infoBase.$refs.FormPanel.form);

      //处理多选数据
      if (allData.ownBrand) {
        allData.ownBrand = allData.ownBrand.join(',');
      }

      //@2
      this.$refs.infoProduct.$refs.FormPanel.excuteFormData(this.$refs.infoProduct.$refs.FormPanel.form);
      allData = Object.assign(allData, this.$refs.infoProduct.$refs.FormPanel.form);

      //@3
      this.$refs.infoPower.$refs.FormPanel.excuteFormData(this.$refs.infoPower.$refs.FormPanel.form);
      allData = Object.assign(allData, this.$refs.infoPower.$refs.FormPanel.form);

      //@4
      this.$refs.infoCompany.$refs.FormPanel.excuteFormData(this.$refs.infoCompany.$refs.FormPanel.form);
      allData = Object.assign(allData, this.$refs.infoCompany.$refs.FormPanel.form);

      //@5
      this.$refs.infoStock.$refs.FormPanel.excuteFormData(this.$refs.infoStock.$refs.FormPanel.form);
      allData = Object.assign(allData, this.$refs.infoStock.$refs.FormPanel.form);

      //@5
      this.$refs.infoFinance.$refs.FormPanel.excuteFormData(this.$refs.infoFinance.$refs.FormPanel.form);
      allData = Object.assign(allData, this.$refs.infoFinance.$refs.FormPanel.form);

      //不再使用由IMG转FILE
      // allData = this.transformAllEnclosure(allData);
      // //@6
      // this.$refs.infoOpinion.excuteFormData(this.$refs.infoOpinion.form);
      // allData = Object.assign(allData,this.$refs.infoOpinion.form);
      if (this.value.type === 'add') {
        //草稿
        allData.auditStatus = types.DEALER_INFO_STATUS_SAVED;
      }

      this.save(allData);
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false });
    },
    infoBaseChange(data) {
      this.$refs.infoProduct.saveDialog();
    },
    infoProductChange(data) {
      this.$refs.infoPower.saveDialog();
    },
    infoPowerChange(data) {
      this.$refs.infoCompany.saveDialog();
    },
    infoCompanyChange(data) {
      this.$refs.infoStock.saveDialog();
    },
    infoStockChange(data) {
      this.$refs.infoFinance.saveDialog();
    },
    infoFinanceChange(data) {
      this.$confirm('是否确定，确定后系统将自动开通账号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (this.generateAsNeeded()) {
            //生成经销商代码，并且创建账号
            if (this.isArcfox()) {
              //生成经销商代码
              data.creatDealerCode = true;
              //生成经销商用户
              data.creatDealerUser = true;
              console.log('这是arcfox，调用生成代码模块');
              this.open(data);
            } else {
              //生成经销商代码
              data.creatDealerCode = true;
              //生成经销商用户
              data.creatDealerUser = true;

              this.loadingVm = this.openLoding('.cover-container');
              //调用提交
              data.auditStatus = types.DEALER_INFO_STATUS_TO_BE_SUBMITTED;
              console.log('这是不是arcfox，调用生成代码模块');
              this.saveDetermine(data);
            }
          } else {
            //不生成账号和经销商code
            this.loadingVm = this.openLoding('.cover-container');
            //调用提交
            //不再使用由IMG转FILE
            // data = this.transformAllEnclosure(data);
            data.auditStatus = types.DEALER_INFO_STATUS_TO_BE_SUBMITTED;
            this.saveDetermine(data);
          }
        })
        .catch(() => {});
    },
    //判断当前是否需要生成经销商代码
    generateAsNeeded() {
      //不存在经销商代码
      return !this.formData.dealerCode;
    },
    open(data) {
      this.$msgbox({
        title: '消息',
        message: (
          <div>
            <el-row class="demo-autocomplete">
              <el-col span={12}>
                <div class="sub-title">数字（1-99）</div>
                <div class="inline-input">
                  <div class="el-input el-input--small">
                    <input
                      type="number"
                      autocomplete="off"
                      min={1}
                      max={99}
                      step={1}
                      precision={0}
                      placeholder="请输入数字（1-99）"
                      v-model={this.formData.inputNumber}
                      class="el-input__inner"
                      onInput={e => {
                        let value = e.target.value;
                        let max = e.target.max;
                        let min = e.target.min;
                        value = String(value).replace(/^\s+|\s+$/g, '');
                        let numberValue = Number(value);
                        if (isNaN(numberValue)) {
                          this.formData.inputNumber = min;
                          e.target.value = min;
                          return;
                        }
                        if (String(value).indexOf('.') != -1) {
                          this.formData.inputNumber = min;
                          e.target.value = min;
                          return;
                        }
                        if (max) {
                          if (!(numberValue <= max)) {
                            this.formData.inputNumber = max;
                            e.target.value = max;
                            return;
                          }
                        }
                        if (min) {
                          if (!(min <= numberValue)) {
                            this.formData.inputNumber = min;
                            e.target.value = min;
                            return;
                          }
                        }
                        this.formData.inputNumber = Number(value);
                        e.target.value = Number(value);
                      }}
                    />
                  </div>
                </div>
              </el-col>
              <el-col span={12}>
                <div class="sub-title">字符（A-Z）</div>
                <div class="inline-input">
                  <div class="el-input el-input--small">
                    <input
                      type="text"
                      maxlength="1"
                      autocomplete="off"
                      placeholder="请输入字符（A-Z）"
                      v-model={this.formData.inputChar}
                      class="el-input__inner"
                      onInput={e => {
                        let value = e.target.value;
                        // if(value){
                        // 	value = value.toLocaleUpperCase();
                        // 	this.$set(this.formData,"inputChar",value);
                        // 	// this.formData.inputChar = value;
                        // 	e.target.inputChar = value;
                        // }
                        // if(/[a-z]/.test(value)){
                        // 	value = value.toLocaleUpperCase();
                        // 	this.formData.inputChar = value;
                        // 	e.target.inputChar = value;
                        // }
                        if (!/[A-Z]/.test(value)) {
                          this.$nextTick(() => {
                            this.$set(this.formData, 'inputChar', '');
                            e.target.inputChar = '';
                          });

                          return;
                        }
                      }}
                    />
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        ),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        closeOnClickModal: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            if (String(this.formData.inputNumber).length == 1) {
              this.formData.inputNumber = '0' + String(this.formData.inputNumber);
            }
            if (!/[A-Z]/.test(this.formData.inputChar)) {
              this.$notify.warning({ title: '提示信息', message: '只可输入【A-Z】!' });
              return false;
            }
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            done();
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = '确定';
          } else {
            done();
          }
        }
      })
        .then(({ value }) => {
          //生成账号
          this.loadingVm = this.openLoding('.cover-container');
          //调用提交
          //不再使用由IMG转FILE
          // data = this.transformAllEnclosure(data);
          data.auditStatus = types.DEALER_INFO_STATUS_TO_BE_SUBMITTED;
          this.saveDetermine(data);
        })
        .catch(() => {});
    },
    // infoOpinionChange(data){
    // this.saveDetermine();
    // },
    //转化表单的附件 转换为list<Map<String,Object>>（提交前使用）
    //不再使用由IMG转FILE
    transformAllEnclosure(data) {
      let rdata = Object.assign({}, data);

      rdata.designFeeEnclosureList = this.transformEnclosureList(rdata.designFeeEnclosureList); //设计费附件
      rdata.cashDepositEnclosureList = this.transformEnclosureList(rdata.cashDepositEnclosureList); //保证金附件

      rdata.businessLicenseEnclosureList = this.transformEnclosureList(rdata.businessLicenseEnclosureList); //营业执照扫描件
      rdata.legalRepresentativeEnclosureList = this.transformEnclosureList(rdata.legalRepresentativeEnclosureList); //法定代表人附件
      rdata.firstPaymentEnclosureList = this.transformEnclosureList(rdata.firstPaymentEnclosureList); //首笔提车款附件

      rdata.openAccountProveEnclosureList = this.transformEnclosureList(rdata.openAccountProveEnclosureList); //开户证明附件

      rdata.licenceEnclosureList = this.transformEnclosureList(rdata.licenceEnclosureList); //许可证附件
      return rdata;
    },
    //转化表单的附件 转换为list<Sting>（回显使用）
    transformAllEnclosureString(data) {
      let rdata = data;

      rdata.designFeeEnclosureList = this.transformEnclosureStringList(rdata.designFeeEnclosureList); //设计费附件
      rdata.cashDepositEnclosureList = this.transformEnclosureStringList(rdata.cashDepositEnclosureList); //保证金附件

      rdata.businessLicenseEnclosureList = this.transformEnclosureStringList(rdata.businessLicenseEnclosureList); //营业执照扫描件
      rdata.legalRepresentativeEnclosureList = this.transformEnclosureStringList(rdata.legalRepresentativeEnclosureList); //法定代表人附件
      rdata.firstPaymentEnclosureList = this.transformEnclosureStringList(rdata.firstPaymentEnclosureList); //首笔提车款附件

      rdata.openAccountProveEnclosureList = this.transformEnclosureStringList(rdata.openAccountProveEnclosureList); //开户证明附件

      rdata.licenceEnclosureList = this.transformEnclosureStringList(rdata.licenceEnclosureList); //许可证附件

      //经销商形式
      let dealerAttachAuthList = [];
      if (isArray(rdata.dealerAttachAuthList)) {
        rdata.dealerAttachAuthList.forEach(x => {
          dealerAttachAuthList.push(x.financeCompanyId);
        });
      }
      rdata.dealerAttachAuthList = dealerAttachAuthList;

      //车系
      let dealerAttachSeriesList = [];
      if (isArray(rdata.dealerAttachSeriesList)) {
        rdata.dealerAttachSeriesList.forEach(x => {
          dealerAttachSeriesList.push(x.seriesId);
        });
      }
      rdata.dealerAttachSeriesList = dealerAttachSeriesList;

      //车型
      let dealerAttachModelList = [];
      if (isArray(rdata.dealerAttachModelList)) {
        rdata.dealerAttachModelList.forEach(x => {
          dealerAttachModelList.push(x.modelId);
        });
      }
      rdata.dealerAttachModelList = dealerAttachModelList;
      return rdata;
    },
    //转换成附件对象 转换为list<Map<String,Object>>
    transformEnclosureList(list) {
      let fileUrlList = [];
      if (!isArray(list)) {
        return fileUrlList;
      }
      //不再使用由IMG转FILE
      // for (let i = 0; i < list.length; i++) {
      // 	let fileUrl = list[i];
      // 	fileUrl = fileUrl.replace(/\\/g,"/");
      // 	fileUrlList.push(Object.assign({},{"name":fileUrl.substring(fileUrl.lastIndexOf('/')+1)},{"url":fileUrl}));
      // }
      // return fileUrlList;
      return list;
    },
    //转换成附件对象(回显) 转换为list<Sting>
    transformEnclosureStringList(list) {
      let fileUrlList = [];
      if (!isArray(list)) {
        return fileUrlList;
      }
      //不再使用由IMG转FILE
      // for (let i = 0; i < list.length; i++) {
      // 	let fileUrl = list[i];
      // 	fileUrlList.push(fileUrl.fileId);
      // }
      list.forEach(x => {
        let id = "";
        if(x.fileId){
          id = x.fileId.indexOf("http://")!=-1?x.fileId.replace("http","https"):x.fileId;
        }
        fileUrlList.push({ name: x.fileName, url: id });
      });
      return fileUrlList;
    },

    async save(data) {
      //保存主表数据
      let res = {};
      if (this.value.type === 'add') {
        res = await addAllData(data);
      } else {
        res = await editAllData(this.value.id, data);
      }
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '保存成功!' });
        this.closeLoding(this.loadingVm);
        this.$emit('close', 'refresh');
      } else {
        this.closeLoding(this.loadingVm);
        this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
      }
    },
    async saveDetermine(data) {
      let res = {};
      if (this.value.type === 'add') {
        res = await addDetermine(data);
      } else {
        res = await editDetermine(this.value.id, data);
      }
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '确认成功!' });
        this.closeLoding(this.loadingVm);
        this.$emit('close', 'refresh');
      } else {
        this.closeLoding(this.loadingVm);
        this.$notify.error({ title: '提示信息', message: res.errMsg || '确认失败!' });
      }
    }
  }
};
</script>

<style scoped>
.wrapper,
.line {
  height: calc(100vh - 135px);
}
.line {
  overflow-x: hidden;
  overflow-y: auto;
}
</style>